package com.twu.biblioteca.models.services;

import com.twu.biblioteca.config.LibaryResourceType;
import com.twu.biblioteca.models.entities.LibaryResource;
import com.twu.biblioteca.models.entities.Movie;
import com.twu.biblioteca.models.entities.Book;

import java.util.ArrayList;
import java.util.List;

import static com.twu.biblioteca.config.LibaryResourceType.*;

public class Libary {
    private static ArrayList<? extends LibaryResource> movies = new ArrayList<Movie>();
    private static ArrayList<? extends LibaryResource> books = new ArrayList<Book>();

    public static List<? extends LibaryResource> getAll(LibaryResourceType resourceType) {
        return getLibaryResourceList(resourceType);
    }

    public static boolean checkout(LibaryResource resource) {
        if (resource != null && resource.isAvailable()) {
            resource.setAvailable(false);
            LibaryResourceType resourceType = resource.getLibaryResourceType();
            List<? extends LibaryResource> resourceList = getLibaryResourceList(resourceType);
            resourceList.remove(resource);
            return true;
        } else {
            return false;
        }
    }

    public static boolean returnBack(LibaryResource resource) {
        if (resource != null && resource.isValid()) {
            resource.setAvailable(true);
            LibaryResourceType resourceType = resource.getLibaryResourceType();
            List<LibaryResource> resourceList = (List<LibaryResource>) getLibaryResourceList(resourceType);
            resourceList.add(resource);
            return true;
        } else {
            return false;
        }
    }

    public static LibaryResource findBy(LibaryResourceType resourceType, String name) {
        for (LibaryResource resource : getLibaryResourceList(resourceType)) {
            if (resource.getName().equals(name)) {
                return resource;
            }
        }
        return null;
    }

    public static boolean add(List<? extends LibaryResource> resources) {
        LibaryResourceType resourceType = resources.get(0).getLibaryResourceType();
        List<LibaryResource> resourceList = (List<LibaryResource>) Libary.getLibaryResourceList(resourceType);
        return resourceList.addAll(resources);
    }

    public static List<? extends LibaryResource> getLibaryResourceList(LibaryResourceType resourceType) {
        if (resourceType == BOOK) {
            return books;
        } else {
            return movies;
        }
    }
}
